﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Tos2Google
{
    public delegate void TD_Login_Callback(string sourceID, string apiVer, string username, string password);

    public partial class TD_Login : Form
	{
        internal static bool Connect(TD_Login_Callback tdLoginCallback)
		{
            TD_Login login = new TD_Login(tdLoginCallback);
			bool connected = login.ShowDialog() == DialogResult.OK; // this "blocks" until window is closed
			login.Dispose();
            return connected;
		}

        public TD_Login_Callback TdLoginCallback { get; private set; }
        public TD_Login(TD_Login_Callback tdLoginCallback)
		{
			InitializeComponent();

            this.DialogResult = DialogResult.Cancel;
            TdLoginCallback = tdLoginCallback;

            autoAdvancer1.BehaveAsAutoLoginWants(AutoLogin.PreferredLoginMethodEnum.AutoLogin/*AutoLogin.StaticThis.PreferredLoginMethod*/);
        }

		#region registry
		protected void Operate_Registry(string sKey, string sParam, ref string sValue, bool bWrite)
		{
			QuickRegistry reg = new QuickRegistry();

			if (!reg.OpenKey("HKEY_CURRENT_USER", sKey, bWrite))
				throw new Exception(reg.ErrorMessage);
			if (reg.GetCurrentKey == null) // doesn't exist
				if (!reg.CreateKey("HKEY_CURRENT_USER", sKey))
					throw new Exception(reg.ErrorMessage);
			if (reg.GetCurrentKey == null)
				throw new Exception("CreateKey failed");
			try
			{
				if (bWrite)
				{
					// write
					if (sValue == null)
						throw new Exception("value@save-to-registry == null");
					if (!reg.SetValue(sParam, sValue))
						throw new Exception(reg.ErrorMessage);
				}
				else
				{
					// read
					string s = (string)reg.GetValue(sParam);
					if (reg.Error)
						throw new Exception(reg.ErrorMessage);
					sValue = s == null ? string.Empty : s;
				}
			}
			finally
			{
				try { reg.Close(true); }
				catch (Exception) { }
			}
		}

        const string RegistryKey = @"Software\Tos2GoogleTeam\Tos2Google";
		void LoadFromRegistry()
		{
			string s = string.Empty;
			Operate_Registry(RegistryKey, "TDSourceID", ref s, false);
			txtSourceID.Text = s;

			Operate_Registry(RegistryKey, "TDUsername", ref s, false);
			txtLoginUsername.Text = s;

			Operate_Registry(RegistryKey, "TDPassword", ref s, false);
			txtLoginPassword.Text = s;

			Operate_Registry(RegistryKey, "TDSavePassword", ref s, false);
			bool savePassword = s == "true";
			checkDontRememberPassword.Checked = !savePassword;

            Operate_Registry(RegistryKey, "TDApiVer", ref s, false);
            txtApiVer.Text = s;

			Operate_Registry(RegistryKey, "SaveDirectory", ref s, false);
			saveFileDialog1.InitialDirectory = s;

			Operate_Registry(RegistryKey, "LoadDirectory", ref s, false);
			openFileDialog1.InitialDirectory = s;

            if (txtSourceID.Text.Length == 0 && txtApiVer.Text.Length == 0 && txtLoginUsername.Text.Length == 0)
            { 
                // most likely the first try
                // fill in the defaults just to get started with something
                txtSourceID.Text = "CZ";
                txtApiVer.Text = "1";
                txtLoginUsername.Text = "CLIFFTON2008";
            }
		}

		void SaveToRegistry()
		{
			string s = txtSourceID.Text;
			Operate_Registry(RegistryKey, "TDSourceID", ref s, true);

			s = txtLoginUsername.Text;
			Operate_Registry(RegistryKey, "TDUsername", ref s, true);

			bool savePassword = !checkDontRememberPassword.Checked;
			if (savePassword)
				s = "true";
			else
				s = "false";
			Operate_Registry(RegistryKey, "TDSavePassword", ref s, true);

			if (savePassword)
				s = txtLoginPassword.Text;
			else
				s = "";
			Operate_Registry(RegistryKey, "TDPassword", ref s, true);

			s = txtApiVer.Text;
			Operate_Registry(RegistryKey, "TDApiVer", ref s, true);

			s = saveFileDialog1.InitialDirectory;
			Operate_Registry(RegistryKey, "SaveDirectory", ref s, true);

			s = openFileDialog1.InitialDirectory;
			Operate_Registry(RegistryKey, "LoadDirectory", ref s, true);
		}
		#endregion

		#region load/save

		private void btnOpen_Click(object sender, EventArgs e)
		{
			openFileDialog1.Filter = "Saved TD logins|*.saved_TD_login";
			openFileDialog1.FilterIndex = 1;
			openFileDialog1.DefaultExt = "saved_TD_login";
			if (openFileDialog1.ShowDialog(this) != DialogResult.OK)
				return;
			SerializableTDLogin serializedLogin =
				SerializableTDLogin.Load(openFileDialog1.FileName) as SerializableTDLogin;

			txtSourceID.Text = serializedLogin.SourceID;
			txtApiVer.Text = serializedLogin.ApiVer;
            txtLoginUsername.Text = serializedLogin.Username;
            txtLoginPassword.Text = serializedLogin.Password;
        }

		private void SaveLogin(bool savePw)
		{
			saveFileDialog1.Filter = "Saved TD logins|*.saved_TD_login";
			saveFileDialog1.FilterIndex = 1;
			saveFileDialog1.DefaultExt = "saved_TD_login";
			if (saveFileDialog1.ShowDialog(this) != DialogResult.OK)
				return;
			SerializableTDLogin serializedLogin =
				new SerializableTDLogin(
					txtSourceID.Text,
					txtApiVer.Text,
					txtLoginUsername.Text,
					(savePw ? txtLoginPassword.Text : string.Empty)
				);
			serializedLogin.Save(saveFileDialog1.FileName);
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			SaveLogin(false);
		}

		private void btnSaveWithPw_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show("Saving with password is a SECURITY RISK!\r\n" +
				"Anyone getting access to that file\r\n" +
				"can see and use the password.\r\n\r\n" +
				"Are you sure you want to do it?",
				"WARNING", MessageBoxButtons.YesNo,
				MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
				return;

			SaveLogin(true);
		}

		#endregion

		private bool Connect()
		{
			if (txtSourceID.Text.Length == 0)
			{
				txtSourceID.Focus();
                MessageBox.Show("Please enter source ID");
				return false;
			}
            if (txtLoginUsername.Text.Length == 0)
            {
                txtLoginUsername.Focus();
                MessageBox.Show("Please enter username");
                return false;
            }
            if (txtLoginPassword.Text.Length == 0)
            {
                txtLoginPassword.Focus();
                MessageBox.Show("Please enter password");
                return false;
            }
            if (txtApiVer.Text.Length == 0)
			{
				txtApiVer.Focus();
				MessageBox.Show("Please enter API version");
				return false;
			}

            TdLoginCallback(txtSourceID.Text, txtApiVer.Text, txtLoginUsername.Text, txtLoginPassword.Text);

			return true;
		}

		private void btnLogin_Click(object sender, EventArgs e)
		{
            if (Connect())
            {
                this.DialogResult = DialogResult.OK;
                Close();
            }
		}

		private void Login_Load(object sender, EventArgs e)
		{
			// the old way: LoadFromRegistry();
            txtSourceID.Text = "CZ";
            txtApiVer.Text = "1";
            txtLoginUsername.Text = AutoLogin.StaticThis.TD_Username;
            txtLoginPassword.Text = AutoLogin.StaticThis.TD_Password;
        }

		private void Login_FormClosing(object sender, FormClosingEventArgs e)
		{
            // the old way: SaveToRegistry();
		}

        private void autoAdvancer1_Go()
        {
            btnLogin_Click(null, null);
        }
	}
}
